package AlexDB.MDB;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

/*
*持久化
*/
public class Persistence {
    private Persistence() {

    }

    private static Persistence persistence = new Persistence();

    public static Persistence getPersistence() {
        return persistence;
    }

    private static File mapProfile = new File("." + File.separator + "db.bin");

    /*
     * 写
     */
    public static void writeDbMapProfile() throws IOException {
        //检查文件是否存在
        if (!mapProfile.getParentFile().exists()) {
            mapProfile.getParentFile().mkdirs();
        }
        //创建文件
        if (!mapProfile.exists()) {
            try {
                mapProfile.createNewFile();
            } 
            catch (IOException e) {
                throw e;
            }
        }

        
        try {
            ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(mapProfile));
            os.writeObject(DataBase.dataMap);
            System.out.println("in " + mapProfile.getName() + " write." + DataBase.dataMap);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /*
     * 读
     */
    public static void readFromListProfile() {

        if (mapProfile.exists() && mapProfile.length() != 0) {
            try {
                ObjectInputStream is = new ObjectInputStream(new FileInputStream(mapProfile));
                var objMap = is.readObject();
                DataBase.dataMap = objMap == null ? DataBase.dataMap : (HashMap<String, Object>) objMap;
                System.out.println(DataBase.dataMap.getClass().getName() + "从文件中读数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * 删
     */
    public static void clearDbMapProfile() {
        if (mapProfile.exists() && mapProfile.length() != 0) {
            try {
                mapProfile.delete();
            } catch (Exception e) {
                throw e;
            }
        }
    }

}
